package com.zfl;

import java.util.PriorityQueue;

public class FindKthLargest {

    public static void main(String[] args) {
        int[] nums = {3,2,1,5,6,4};
        int k = 2;
        int kthLargest = new FindKthLargest().findKthLargest(nums,2);
        System.out.println("kthLargest = " + kthLargest);
    }

    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();

        for (int num : nums) {
            if (queue.size()<k) {
                queue.offer(num);
            }else {
                if (num>queue.peek()) {
                    queue.poll();
                    queue.offer(num);
                }
            }
        }

        return queue.peek();
    }
}
